const path = require('path')
const glob = require('glob')
// 工厂函数 - 配置pages实现多页面获取某文件夹下的html与js
function handleEntry (entry) {
  const entries = {}
  let entryBaseName = ''
  let entryPathName = ''
  let entryTemplate = ''

  glob.sync(entry).forEach(item => {
    // console.log('!!!', item)
    entryBaseName = path.basename(item, path.extname(item))
    // console.log('entryBaseName:', entryBaseName)
    entryTemplate = item.split('/').splice(-3)
    // console.log('entryTemplate:', entryTemplate)
    entryPathName = entryBaseName // 正确输出js和html的路径
    // console.log('entryPathName', entryPathName)

    entries[entryPathName] = {
      entry: 'src/pages/' + entryPathName + '/' + entryPathName + '.js',
      template: 'src/modules/' + entryTemplate[2],
      title: entryTemplate[2],
      filename: entryTemplate[2]
    }
  })
  return entries
}

const pages = handleEntry('./src/modules/*.html')
console.log(pages)
// 以下开始配置
module.exports = {
  lintOnSave: true, // 关掉eslint
  productionSourceMap: false,
  // 入口设置
  pages,
  devServer: {
    index: '/', // 运行时，默认打开application1页面
    // 告诉dev-server在服务器启动后打开浏览器，将其设置true为打开默认浏览器
    open: true,
    port: 9900,
    https: false,
    hotOnly: false,
    // 配置首页 入口链接
    before: app => {
      app.get('/', (req, res, next) => {
        for (const i in pages) {
          res.write(`<a target="_self" href="/${i}">/${i}</a></br>`)
        }
        res.end()
      })
    }
  }
}
